import requests
import re
from urllib.parse import unquote

PLAY_INFO_PATTERN = re.compile(r"vod-play-id-(\d+)-src-(\d+)-num-(\d+).html")
USER_AGENT = "Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/97.0.4692.71 Mobile Safari/537.36"


def decode_url(url):
    """
    解析链接
    :param url: 链接m.88kan.tv播放页面链接
    :return: {id, playIndex, ep}
    """
    info = PLAY_INFO_PATTERN.findall(url)[0]
    return {
        "id": int(info[0]),
        "playIndex": int(info[1]),
        "ep": int(info[2])
    }


def decodeMacUrl(data: str):
    tmp = []
    for page in data.split("$$$"):
        playList = []
        for item in page.split("#"):
            playList.append(item.split("$"))
        tmp.append(playList)
    return tmp


def find_val(htmlContent, valueName):
    index = 0
    for key in [valueName, "'"]:
        if index > -1:
            index = htmlContent.find(key, index)
    if index > -1:
        index += 1
        return htmlContent[index: htmlContent.find("'", index)]
    return None


def decodeMacFrom(text: str):
    return text.split("$$$")


def find_play_url_data(htmlContent: str):
    return {
        'macName': find_val(htmlContent, "mac_name"),
        'macUrl': decodeMacUrl(escape(unquote(find_val(htmlContent, "mac_url")))),
        'macFrom': decodeMacFrom(find_val(htmlContent, "mac_from")),
    }


def escape(text: str):
    text = text.replace("%", "\\")
    return text.encode("utf-8").decode("unicode_escape")


def get_play_url_list(url):
    htmlContent = requests.get(url=url, headers={
        "user-agent": USER_AGENT
    }).text
    return find_play_url_data(htmlContent)


def get_play_list(url):
    """
    获取下载播放连接
    :param url: 播放地址
    :return: 结果
    """
    info = decode_url(url=url)
    data = get_play_url_list(url=url)
    return {
        "name": data['macName'],
        "url": data['macUrl'][info['playIndex'] - 1],
        "ep": info['ep']
    }
